import {
    Image,
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    SafeAreaView,
    TextInput,
    Animated,
    useWindowDimensions,
    ActivityIndicator,
    FlatList,
    RefreshControl,
    Modal,
    ImageBackground,
    Dimensions,
    Alert
} from 'react-native';
import {router, Stack, useLocalSearchParams, useRouter} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import { useCallback, useEffect, useState, useRef, useImperativeHandle, forwardRef} from "react";
import Octicons from '@expo/vector-icons/Octicons';
import Ionicons from '@expo/vector-icons/Ionicons';
import AntDesign from '@expo/vector-icons/AntDesign';
import * as React from "react";
import { TabView, SceneMap } from "react-native-tab-view";
import empty_icon from "@/assets/images/concern/empty_fan.png";
import activityTag from "@/assets/images/collection/activityTag.png";
import dateTimeIcon from "@/assets/images/collection/dateTime.png";
import addressIcon from "@/assets/images/collection/address.png";
import { useSafeAreaInsets } from "react-native-safe-area-context"
import CarouselComponent from "@/components/CarouselComponent";
import SwiperActivityItemComponent from "@/components/SwiperActivityItem";
import TagBg from "@/assets/images/homeImg/tagBg.png";
import TagScrollView from "@/components/TagScrollView";
import avator from "@/assets/images/me/avator.png";
import { getSearchKeyWordListRequest, getSearchHistoryList, cleanhistoryByRequest } from "@/services/activityServices"
import { parseFloat } from "@/utils/index"
import {differenceInHours, format, isValid} from "date-fns";
import NomoreComponent from "@/components/NomoreComponent/index"
import Empty from "@/components/empty/index"
import {useSelector} from "react-redux";
import {RootState} from "@/store";
import {getSpaceRecommendListByRequest, getSpaceSearchByRequest} from "@/services/spaceServices";
import CustomFlatList from "@/components/CustomFlatList";
import { getSearchCoummunityListByRequest } from "@/services/registerCommumity"



const { width } = Dimensions.get('window');

const images = [
    'https://via.placeholder.com/800x400.png?text=Slide+1',
    'https://via.placeholder.com/800x400.png?text=Slide+2',
    'https://via.placeholder.com/800x400.png?text=Slide+3',
];

const JoinRoute = forwardRef(({ keywork }, ref) => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [refreshing, setRefreshing] = useState(false);
    const [triggerRefresh, setTriggerRefresh] = useState(false);
    const [page, setPage] = useState(1);
    const [refreshingText, setRefreshingText] = useState('下拉刷新');
    const scrollY = new Animated.Value(0);
    const [current, setCurrent] = useState(1);
    const [size, setSize] = useState(5);
    const [pages, setPages] = useState(0);
    const [noMore, setNoMore] = useState(false);

    const login = useSelector((state: RootState) => state.login);

    const router = useRouter();

    const goActivityDetail = function (id) {
        router.push(`/activityDetail/${id}`)
    };


    useImperativeHandle(ref, () => ({
        getList
    }));

    const getList = function (params?:any = {}) {
        console.log('params', params);
        const requestData = {
            word: keywork || "",
            province: login?.locationInfo?.province ||"",
            city: login?.locationInfo?.city || "",
            current: 1,
            size: 5,
            ...params,
        };

        console.log('requestData', requestData);


        setLoading(true);
        getSearchKeyWordListRequest(requestData)
            .then((res) => {
                console.log('getSearchKeyWordListRequest', res);
                if (requestData?.current == 1) {
                    setData([...res?.data?.items]);
                } else {
                    setData([...data, ...res?.data?.items]);
                };

                setPages(res?.data?.pages);
                setCurrent(res?.data?.current);
                setLoading(false);
                setRefreshing(false)
            })
            .catch(err => {
                setRefreshing(false);
                console.log('err', err);
            })
    };

    useEffect(() => {
        getList();
    }, [])

    // 自定义加载图标组件
    const RefreshControlHeader = ({ refreshing, text }) => (
        refreshing && (
            <View style={styles.refreshHeader}>
                <Text style={styles.refreshText}>{text}</Text>
            </View>
        )
    );

    useEffect(() => {
        if (triggerRefresh) {
            handleRefresh();
            setTriggerRefresh(false); // Reset trigger
        }
    }, [triggerRefresh]);

    const loadMoreData = () => {
        if (loading) return;

        setLoading(true);
        if (current === pages) {
            setLoading(false)
            setNoMore(true)
            return;
        };
        // 模拟网络请求来获取更多数据
        const params = {
            current: current + 1,
        }
        getList(params)
    };

    const handleRefresh = () => {
        setRefreshing(true);
        setRefreshingText('正在刷新...');
        setPage(1);
        getList({ current: 1 })
    };


    const renderFooter = () => {
        if (!loading) return null;
        if (data.length <= 0) return null;
        return (
            <>
                {
                    loading && (
                        <View style={{ paddingVertical: 10, flexDirection: "row", justifyContent: "center", alignItems: "center" }}>
                            <ActivityIndicator size="small" />
                            <Text style={{ textAlign: 'center', fontSize: 14, color: "#676978", marginLeft: 5, }}>疯狂加载中</Text>
                        </View>
                    )
                }
            </>
        );
    };




    const handleScroll = Animated.event(
        [{ nativeEvent: { contentOffset: { y: scrollY } } }],
        {
            useNativeDriver: false,
            listener: event => {
                const offsetY = event.nativeEvent.contentOffset.y;

                if (!refreshing) {
                    // 根据下拉距离更新文本
                    if (offsetY < -100) {
                        setRefreshingText('松开刷新'); // 超过 -100 的偏移量显示松开刷新
                    } else if (offsetY < 0) {
                        setRefreshingText('下拉刷新'); // 在 -100 到 0 之间时显示下拉刷新
                    }
                }
            },
        }
    );

    const onScrollEnd = () => {
        scrollY.addListener(({ value }) => {
            if (!refreshing && value < -100) {
                setTriggerRefresh(true); // 触发刷新
            }
        });
    };

    const computedTime = function (startT, endT) {
        const year1 = format(startT, "yyyy");
        const year2 = format(endT, "yyyy");
        const day1 = format(startT, "MMdd");
        const day2 = format(endT, "MMdd");
        const time1 = format(startT, "HH:mm");
        const time2 = format(endT, "HH:mm");

        // 计算两个时间之间的小时差
        const hoursDiff = differenceInHours(endT, startT);

        // 如果起始时间和结束时间都是 00:00，并且时间跨度是 24 小时的整数倍
        if (time1 === "00:00" && time2 === "00:00" && hoursDiff % 24 === 0) {
            if (year1 !== year2) {
                return `${format(startT, "yyyy.MM.dd")}-${format(endT, "yyyy.MM.dd")}`;
            }
            return `${format(startT, "MM.dd")}-${format(endT, "MM.dd")}`;
        }

        if (day1 === day2) {
            if (year1 !== year2) {
                return `${format(startT, "yyyy.MM.dd")} ${format(startT, "HH:mm")}-${format(endT, "HH:mm")}`;
            }
            return `${format(startT, "MM.dd")} ${format(startT, "HH:mm")}-${format(endT, "HH:mm")}`;
        }

        if (year1 !== year2) {
            return `${format(startT, "yyyy.MM.dd")} ${format(startT, "HH:mm")}-${format(endT, "yyyy.MM.dd")} ${format(endT, "HH:mm")}`;
        }

        return `${format(startT, "MM.dd")} ${format(startT, "HH:mm")}-${format(endT, "MM.dd")} ${format(endT, "HH:mm")}`;
    };



    const ActivityItem = ({ item }) => {
        return (
            <TouchableOpacity onPress={() => goActivityDetail(item.activityId)}>
                <View style={styles.activityContainer}>
                    <View style={styles.activitybody}>
                        <View style={styles.activityBanner}>
                            <Image source={{ uri: item?.coverUrl }} style={{ width: "100%", height: "100%" }} />
                            <ImageBackground source={activityTag} style={styles.activityTagWarp}>
                                <Text style={styles.tagText}>{ item.typeName }</Text>
                            </ImageBackground>

                        </View>
                        <View style={styles.activityContent}>
                            <View style={styles.activityTitleWarp}>
                                <Text
                                    style={styles.activityTitle}
                                    numberOfLines={2}
                                    ellipsizeMode="tail"
                                >{ item.title }</Text>
                            </View>
                            <View style={{ flexDirection: "row" }}>
                                {
                                    item?.tags?.map((it: any, index: number) => {
                                        return (
                                            <View style={styles.activityTag} key={index}>
                                                <Text style={styles.activityTagText}>{ it }</Text>
                                            </View>
                                        )
                                    })
                                }
                            </View>

                            <View style={styles.activityDateWarp}>
                                <View style={styles.addressIcon}>
                                    <Image source={dateTimeIcon} style={{ width: '100%', height: "100%" }} />
                                </View>
                                <Text style={ styles.activityDate }>{ computedTime(item?.durationStartTime, item?.durationEndTime) }</Text>
                            </View>
                            <View style={styles.activityAdressWarp}>
                                <View style={styles.addressIcon}>
                                    <Image source={addressIcon} style={{ width: '100%', height: "100%" }} />
                                </View>
                                <Text style={styles.activityAdress}>{ item.destName }</Text>
                            </View>
                        </View>
                    </View>
                    <View style={styles.activityFooter}>
                        <View style={styles.joinList}>
                            <View style={styles.joinListWarp}>
                                {
                                    item.members.map((it:any, index: number) => {
                                        if (index == 0) {
                                            return (
                                                <View style={styles.joinAvator}>
                                                    <Image source={{ uri: it.avator }} style={{ width: "100%", height: "100%" }} />
                                                </View>
                                            )
                                        } else if (index <= 3 ) {
                                            return (
                                                <View style={[styles.joinAvator,styles.maLeft]}>
                                                    <Image source={{ uri:it.avator }} style={{ width: "100%", height: "100%" }} />
                                                </View>
                                            )
                                        }
                                    })
                                }

                            </View>
                            {
                                item.activityStatus == 1 && (
                                    <View style={styles.joinContent}>
                                        <Text style={styles.joinContentText}>正在招募...</Text>
                                    </View>
                                )
                            }
                        </View>
                        <View style={styles.activityMoney}>
                            <Text style={styles.activityMoneyText}>¥{ parseFloat(item?.ticketsPrice) }</Text>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        )
    };

    return (
        <View style={{ backgroundColor: "#F7F7F7", flex: 1 }}>
            <FlatList
                data={data}
                renderItem={({ item }) => <ActivityItem item={item}/>}
                keyExtractor={(item, index) => index.toString()}
                onEndReached={loadMoreData}
                onEndReachedThreshold={0.5} // 当滚动到距离底部还有50%的时候触发
                ListFooterComponent={renderFooter}
                refreshControl={
                    <RefreshControl
                        refreshing={refreshing}
                        // onRefresh={handleRefresh} // 绑定刷新函数
                        title={refreshing ? '' : refreshingText} // 在正在刷新状态时不显示文本
                        titleColor="#333" // 设置提示文字颜色
                        tintColor="transparent" // 隐藏刷新指示器
                    />
                }
                onScroll={handleScroll}
                onScrollEndDrag={onScrollEnd}
                ListHeaderComponent={<RefreshControlHeader refreshing={refreshing} text={refreshingText} />}
                ListEmptyComponent={<Empty title="空空如也～"/>}
            />
        </View>
    );
});

const CreateRoute = forwardRef(({ keywork }, ref) => {
    const [data, setData] = useState([]);
    const [refreshing, setRefreshing] = useState(false);
    const [loadingMore, setLoadingMore] = useState(false);
    const [page, setPage] = useState(1);
    const [totalPages, setTotalPages] = useState(0); //数据总量
    const [totalCount, setTotalCount] = useState(0); // 总分页数


    const login = useSelector((state: RootState) => state.login);

    const router = useRouter();

    const goActivityDetail = function (id) {
        router.push(`/activityDetail/${id}`)
    };


    useImperativeHandle(ref, () => ({
        fetchData
    }));

    console.log('searchTextsearchText', keywork);

    const fetchData = async ({ pageNum = 1, word = "" }, isRefreshing = false) => {
        if (isRefreshing) {
            setRefreshing(true);
        } else {
            setLoadingMore(true);
        };

        const requestData = {
            current: page,
            size: 10,
            word: word,
        };

        getSearchCoummunityListByRequest(requestData)
            .then((res: any) => {
                const newData = res?.data?.items;
                console.log('res', res);
                setData(prevData => (isRefreshing ? newData : [...prevData, ...newData]));
                setPage(pageNum);
                setTotalPages(res?.data?.counts);
                setTotalCount(res?.data?.pages)
                setRefreshing(false);
                setLoadingMore(false);
            })
            .catch(err => {
                setRefreshing(false);
                setLoadingMore(false);
                console.log('err', err);
            })
    };


    useEffect(() => {
        fetchData({ pageNum: 1, word: keywork }, true);
    }, [])

    // 自定义加载图标组件
    const RefreshControlHeader = ({ refreshing, text }) => (
        refreshing && (
            <View style={styles.refreshHeader}>
                <Text style={styles.refreshText}>{text}</Text>
            </View>
        )
    );

    const onRefresh = () => {
        fetchData({ pageNum: 1, word: keywork }, true);
    };

    const onLoadMore = () => {
        if (page == totalCount) {
            setRefreshing(false);
            setLoadingMore(false);
            return
        };
        if (page < totalPages) {
            fetchData({ pageNum: page + 1, word: keywork });
        }
    };

    const renderItem = ({ item }) => {
        return (
            <TouchableOpacity>
                <View style={styles.koneItem}>
                    <View style={styles.koneAvator}>
                        <Image source={{ uri: item.coverUrl }} style={{ width: "100%", height: "100%" }} />
                    </View>
                    <View style={styles.koneContent}>
                        <Text style={styles.koneContentText}>{ item?.name }</Text>
                    </View>
                    <View>
                        <AntDesign name="right" size={8} color="#9C9EAC" />
                    </View>
                </View>
            </TouchableOpacity>
        )
    };

    const goJoinGroupPages = function (groupId) {
        router.push(`/registerGroup/applyJoinGroup/${groupId}`)
    };

    const goGroupDetail = function (groupId) {
        router.push(`/registerGroup/groupDetail/${groupId}`)
    };

    const ActivityItem = ({ item }) => {
        const { type } = item;
        // console.log('ActivityItemActivityItem', item);
        return (
            <View style={styles.groupContainer}>
                <View style={styles.groupStateContainer}>
                    <TouchableOpacity onPress={() => goGroupDetail(item.communityId)}>
                        <View style={styles.groupInfoWarp}>
                            <View style={styles.groupAvator}>
                                {/*<Text>ava</Text>*/}
                                <Image source={{ uri: item?.coverUrl }} style={{ width: "100%", height: '100%' }} />
                            </View>
                            <View style={styles.groupInfoCotent}>
                                <View>
                                    <Text style={styles.groupInfoTitle}>{ item?.name }</Text>
                                </View>
                                <View style={{ marginTop: 6 }}>
                                    <Text style={styles.groupInfoTotal}>成员数:{ item?.memberNum }人</Text>
                                </View>
                            </View>
                        </View>
                    </TouchableOpacity>

                    {
                        item?.relationship == 1 && (
                            <TouchableOpacity onPress={() => goJoinGroupPages(item?.communityId)}>
                                <View style={styles.groupCreateBtn}>
                                    <Text style={styles.groupCreateBtnText}>加入</Text>
                                </View>
                            </TouchableOpacity>
                        )
                    }

                    {
                        item?.relationship == 2 && (
                            <TouchableOpacity onPress={() => goGroupDetail(item?.communityId)}>
                                <View style={styles.groupCreateBtn}>
                                    <Text style={styles.groupCreateBtnText}>审核中</Text>
                                </View>
                            </TouchableOpacity>
                        )
                    }

                    {
                        item?.relationship == 3 && (
                            <TouchableOpacity onPress={() => goGroupDetail(item?.communityId)}>
                                <View style={styles.groupCreateBtn}>
                                    <Text style={styles.groupCreateBtnText}>已加入</Text>
                                </View>
                            </TouchableOpacity>
                        )
                    }


                </View>
                {
                    item?.activityList.length > 0 && (
                        <View style={{ paddingHorizontal: 12 }}>
                            <CarouselComponent
                                loop
                                width={scaleSize(351)}
                                height={width * 0.32}
                                data={item?.activityList}
                                scrollAnimationDuration={1000}
                                initialScrollIndex={0}  // 设置初始滚动索引
                                renderItem={({ item }) => {
                                    return <SwiperActivityItemComponent showPrice={false} item={item} />
                                }}
                            />
                        </View>
                    )
                }

            </View>
        )
    };

    const ActivityItemCallBack = useCallback(({ item }) => (
        <ActivityItem item={item}/>
    ), []);

    return (
        <View style={styles.koneContainer}>
            <CustomFlatList
                data={data}
                keyExtractor={(item, index) => index.toString()}
                onRefresh={onRefresh}
                onLoadMore={onLoadMore}
                refreshing={refreshing}
                loadingMore={loadingMore}
                renderItem={ActivityItemCallBack}
                totalCount={totalCount}
                currentPage={page}
                totalPages={totalPages}
            />
        </View>
    );
});

const WaitRoute = forwardRef(({ keywork }, ref) => {
    const [data, setData] = useState([]);
    const [refreshing, setRefreshing] = useState(false);
    const [loadingMore, setLoadingMore] = useState(false);
    const [page, setPage] = useState(1);
    const [totalPages, setTotalPages] = useState(0); //数据总量
    const [totalCount, setTotalCount] = useState(0); // 总分页数

    const login = useSelector((state: RootState) => state.login);

    const goSpaceDetail = function () {
        router.push("/space/2")
    };

    useImperativeHandle(ref, () => ({
        fetchData
    }));

    useEffect(() => {
        fetchData({ pageNum: 1, word: keywork }, true);
    }, [])

    const fetchData = async ({ pageNum = 1, word = "" }, isRefreshing = false) => {
        if (isRefreshing) {
            setRefreshing(true);
        } else {
            setLoadingMore(true);
        };

        const requestData = {
            province: login?.locationInfo?.province || "",
            city: login?.locationInfo?.city || "",
            current: page,
            size: 10,
            word: word,
        };
        console.log('requestData', requestData);

        getSpaceSearchByRequest(requestData)
            .then((res: any) => {
                const newData = res?.data?.items;
                console.log('res', res);
                setData(prevData => (isRefreshing ? newData : [...prevData, ...newData]));
                setPage(pageNum);
                setTotalPages(res?.data?.counts);
                setTotalCount(res?.data?.pages)
                setRefreshing(false);
                setLoadingMore(false);
            })
            .catch(err => {
                setRefreshing(false);
                setLoadingMore(false);
                console.log('err', err);
            })
    };

    const onRefresh = () => {
        fetchData({ pageNum: 1, word: keywork }, true);
    };

    const onLoadMore = () => {
        if (page == totalCount) {
            setRefreshing(false);
            setLoadingMore(false);
            return
        };
        if (page < totalPages) {
            fetchData({ pageNum: page + 1 });
        }
    };

    const renderItem = ({ item }) => {
        return (
            <TouchableOpacity onPress={goSpaceDetail}>
                <View style={styles.koneItem}>
                    <View style={styles.koneAvator}>
                        <Image source={{ uri: item.coverUrl }} style={{ width: "100%", height: "100%" }} />
                    </View>
                    <View style={styles.koneContent}>
                        <Text style={styles.koneContentText}>{ item?.name }</Text>
                    </View>
                    <View>
                        <AntDesign name="right" size={8} color="#9C9EAC" />
                    </View>
                </View>
            </TouchableOpacity>
        )
    };

    return (
        <View style={styles.koneContainer}>
            <CustomFlatList
                data={data}
                keyExtractor={(item, index) => index.toString()}
                onRefresh={onRefresh}
                onLoadMore={onLoadMore}
                refreshing={refreshing}
                loadingMore={loadingMore}
                renderItem={renderItem}
                totalCount={totalCount}
                currentPage={page}
                totalPages={totalPages}
            />
        </View>
    )
});



const CustomTabBar = ({ navigationState, position, setIndex }) => {
    // 创建指示器的动态宽度和位置
    const inputRange = navigationState.routes.map((_, i) => i);
    const layoutWith = scaleSize(350);
    const translateX = position.interpolate({
        inputRange,
        outputRange: inputRange.map(i => i * layoutWith / 3 + ((layoutWith / 3) - layoutWith / 13) / 2),
        // outputRange: [48, 162], // 这里的值需要根据实际情况计算
    });


    return (
        <View style={styles.tabHeader}>
            <View style={styles.tabBar}>
                {navigationState.routes.map((route, i) => (
                    <TouchableOpacity
                        key={route.key}
                        onPress={() => setIndex(i)}
                        style={styles.tabItem}>
                        <Text style={{ color: navigationState.index === i ? '#EC6138' : 'black', textAlign: "left" }}>
                            {route.title}
                        </Text>
                    </TouchableOpacity>
                ))}
                {/* 自定义指示器 */}
                <Animated.View
                    style={[
                        styles.indicator,
                        { transform: [{ translateX }] },
                        { width: scaleSize(26) } // 指示器的宽度
                    ]}
                />
            </View>
        </View>
    );
};


export default function searchActivityScreen() {
    const [searchText, setSearchText] = useState('');
    const [index, setIndex] = React.useState(0);
    const [isFocus, setIsFocus] = useState(false);
    const [historyList, setHistoryList] = useState([]);

    const inputRef = useRef(null);
    const searchRef = useRef(null);
    const spaceRef = useRef(null);
    const groupRef = useRef(null);

    const routerParams = useLocalSearchParams();

    const [routes] = React.useState([
        { key: 'join', title: '活动' },
        { key: 'create', title: '社群' },
        { key: 'check', title: '空间' },
    ]);

    useEffect(() => {
        getHistoryListByRequest();
        setTimeout(() => {
            setIndex(Number(routerParams?.index));
        }, 0)
    }, [])

    const getHistoryListByRequest = function () {
        getSearchHistoryList()
            .then(res => {
                setHistoryList(res.data.history)
            })
            .catch(err => {
                console.log('err', err);
            })
    };

    const layout = useWindowDimensions();
    const inner = useSafeAreaInsets();

    const renderScene = ({ route }) => {
        switch (route.key) {
            case 'join':
                return <JoinRoute currentIndex={index} key={'join'} keywork={searchText} ref={searchRef}/>; // 传递当前索引给 FirstRoute
            case 'create':
                return <CreateRoute currentIndex={index} key={'create'} keywork={searchText} ref={groupRef}/>;
            case 'check':
                return <WaitRoute currentIndex={index} key={'check'} keywork={searchText} ref={spaceRef} />;
            default:
                return null;
        }
    };
    const handleClearText = () => {
        setSearchText('');
        inputRef?.current?.blur();
        if (searchRef?.current && index == 0) {
            searchRef?.current?.getList({ current: 1, word: "" });
        } else if(spaceRef?.current && index == 2) {
            spaceRef?.current?.fetchData({ pageNum: 1, word: "" }, true);
        } else if (groupRef?.current && index == 1) {
            groupRef?.current?.fetchData({ pageNum: 1, word: "" }, true);
        };
    };


    useEffect(() => {
    }, []);

    const onSearch = function () {
        inputRef?.current?.blur();
        console.log('searchRef?.current', searchRef?.current);
        if (searchRef?.current && index == 0) {
            searchRef?.current?.getList({ current: 1, word: searchText });
        } else if(spaceRef?.current && index == 2) {
            spaceRef?.current?.fetchData({ pageNum: 1, word: searchText }, true);
        } else if (groupRef?.current && index == 1) {
            groupRef?.current?.fetchData({ pageNum: 1, word: searchText }, true);
        };
    };

    const clickSearch = function (keWork) {
        setSearchText(keWork);
        setIsFocus(false);
        console.log('searchRef', searchRef.current)
        if (searchRef?.current && index == 0) {
            searchRef?.current?.getList({ current: 1, word: keWork });
        } else if(spaceRef?.current && index == 2) {
            spaceRef?.current?.fetchData({ pageNum: 1, word: keWork }, true);
        } else if (groupRef?.current && index == 1) {
            groupRef?.current?.fetchData({ pageNum: 1, word: keWork }, true);
        };
        setTimeout(() => {
            getHistoryListByRequest();
        }, 2000)
    };

    const cleanHistory = function () {
        Alert.alert(
            "",
            "历史记录清除后无法恢复,是否清除全部记录？",
            [
                { text: "取消", onPress: () => console.log("取消"), style: "cancel" },
                { text: "清除", onPress: () => {
                    cleanhistoryByRequest()
                        .then(res => {
                            console.log('err', res)
                            getHistoryListByRequest();
                        })
                        .catch(err => {
                            console.log('err', err);
                        })
                }}
            ],
            { cancelable: true } // 是否允许点击外部区域关闭
        );
    };


    return (
        <View style={{ height: "100%", backgroundColor: "#fff" }}>
            <Stack.Screen
                options={{
                    headerShown: false
                }}
            />
            <View style={{ paddingHorizontal: 12, paddingTop: inner.top }}>
                <View style={styles.searchContainer}>
                    <View style={styles.container}>
                        <Octicons name="search" size={15} color="#2A2B30" style={styles.inptSearchIcon} />
                        <TextInput
                            ref={inputRef}
                            style={styles.inpt}
                            placeholder="搜活动、俱乐部"
                            value={searchText}
                            onChangeText={setSearchText}
                            onFocus={(bol) => {
                                console.log(bol)
                                setIsFocus(true)
                            }}
                            onBlur={() => setIsFocus(false)}
                        />
                        {
                            searchText.length > 0 && (
                                <TouchableOpacity onPress={handleClearText} style={styles.closeIcon}>
                                    <Ionicons name="close-circle-sharp" size={20} color="#C0C3CE" />
                                </TouchableOpacity>
                            )
                        }
                    </View>
                    <TouchableOpacity onPress={onSearch}>
                        <View style={styles.searchBtn}>
                            <Text style={styles.searchBtnText}>搜索</Text>
                        </View>
                    </TouchableOpacity>

                    {/*{*/}
                    {/*    false && (*/}
                    {/*        <TouchableOpacity>*/}
                    {/*            <View style={styles.searchBtn}>*/}
                    {/*                <Text style={styles.searchBtnText}>取消</Text>*/}
                    {/*            </View>*/}
                    {/*        </TouchableOpacity>*/}
                    {/*    )*/}

                    {/*}*/}
                </View>

            </View>
            {
                isFocus && (

                    <TouchableOpacity style={{ paddingHorizontal: 12, height: "100%" }} onPress={() => {
                        setIsFocus(false);
                    }}>
                        <View style={styles.historyContainer}>
                            <Text style={styles.historyTitle}>历史搜索</Text>
                            <TouchableOpacity onPress={cleanHistory}>
                                <View style={styles.clearHistory}>
                                    <AntDesign name="delete" size={12} color="#9C9EAC" />
                                    <Text style={styles.clearText}>清空</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={styles.searchHistyListContaier}>
                            {
                                historyList.map((item: any, index: number) => {
                                    if (item) {
                                        return (
                                            <TouchableOpacity key={index} onPress={() => clickSearch(item)}>
                                                <View style={styles.historyItem}>
                                                    <Text style={styles.historyItemText}>{ item }</Text>
                                                </View>
                                            </TouchableOpacity>
                                        )
                                    };
                                })
                            }
                        </View>
                    </TouchableOpacity>
                )
            }

            {
                <TabView
                    navigationState={{ index, routes }}
                    renderScene={renderScene}
                    onIndexChange={setIndex}
                    initialLayout={{ width: layout.width }}
                    renderTabBar={
                        (props) => <CustomTabBar {...props} setIndex={setIndex} />
                    }
                    style={{ marginTop: 5 }}
                />
            }

        </View>

    );
}

const styles = StyleSheet.create({
    searchContainer: {
        flexDirection: "row",
        alignItems: "center",
        // backgroundColor: "blue"
    },
    inpt: {
        flex: 1,
        height: 30,
        borderWidth: 1,
        borderRadius: 15,
        borderColor: "#2A2B30",
        paddingHorizontal: 30,
        fontSize: 12,
        color: "#2A2B30"
    },
    searchBtn: {
        paddingHorizontal: 3,
        paddingLeft: 15,
    },
    searchBtnText: {
        color: "#EC6138"
    },
    container: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
        position:"relative",
    },
    inptSearchIcon: {
        position: "absolute",
        left: 12,
    },
    closeIcon: {
        position: "absolute",
        right: 5,
        top: 4,
    },
    historyContainer: {
        flexDirection: "row",
        justifyContent: "space-between",
        marginTop: 20,
    },
    clearHistory: {
        flexDirection: "row",
        alignItems: "center",
    },
    historyTitle: {
        color: "#2A2B30",
        fontSize: 12,
    },
    clearText: {
        marginLeft: 2,
        fontSize: 12,
        color: "#9C9EAC",
    },
    searchHistyListContaier: {
        flexDirection: "row",
        marginTop: 16,
        alignItems: "center",
        flexWrap: "wrap",
    },
    historyItem: {
        backgroundColor: "#FAFAFA",
        paddingHorizontal: 10,
        marginVertical: 4,
        borderRadius: 10,
        marginRight: 8,
        marginBottom:  10,
    },
    historyItemText: {
        fontSize: 12,
        color: "#2A2B30"
    },
    scene: {
        flex: 1,
        // justifyContent: 'center',
        // alignItems: 'center',
    },
    tabBar: {
        flexDirection: 'row',
        backgroundColor: 'white',
        position: 'relative', // 需要相对定位来放置指示器
        width:scaleSize(350),
        margin: "auto",
    },
    tabItem: {
        flex: 1,
        alignItems: 'center',
        paddingTop: 10,
        paddingBottom: 9,
        fontSize: 14,
        color: "#2A2B30",
    },
    indicator: {
        position: 'absolute',
        height: 3,
        backgroundColor: '#EC6138',
        bottom: 0,
        borderRadius: 5,
    },
    tabHeader: {
        backgroundColor: "#fff",
        borderBottomWidth: 1,
        borderBottomColor: "#F1F2F5",
        // marginBottom: 12,
    },
    activityContainer: {
        // flexDirection: "row",
        marginLeft: 12,
        marginRight: 12,
        height: scaleSize(164),
        backgroundColor: "#fff",
        borderRadius: 8,
        marginBottom: 12,
    },
    activitybody: {
        padding: 12,
        flexDirection: "row",

    },
    activityBanner: {
        position: "relative",
        width: scaleSize(110),
        height: scaleSize(110),
        // backgroundColor: "blue",
        borderRadius: 4,
    },
    activityContent: {
        marginLeft: 10,
    },
    activityTitleWarp: {
        width: scaleSize(192),
    },
    activityTitle: {
        fontSize: 16,
        fontWeight: "bold",
        color: "#2A2B30",
        letterSpacing: 1.2,
        lineHeight: 22,
    },
    addressIcon: {
        width: scaleSize(11),
        height: scaleSize(11),
    },
    activityTag: {
        width: scaleSize(28),
        height: scaleSize(12),
        backgroundColor: "rgba(255,70,0,0.1)",
        borderRadius: 10,
        marginTop: 6,
    },
    activityTagText: {
        fontSize: 8,
        color: "#EC6138",
        textAlign: "center",
        lineHeight: 12,
    },
    activityDateWarp: {
        flexDirection: "row",
        alignItems: "center",
        marginTop: 6,
        marginBottom: 6,
    },
    activityDate: {
        marginLeft: 3,
        fontSize: 12,
        color: "#676978"
    },
    activityAdressWarp: {
        flexDirection: "row",
        alignItems: "center",
    },
    activityAdress: {
        fontSize: 12,
        color: "#676978",
        marginLeft: 3,
    },
    joinList: {
        flexDirection: "row",
        alignItems: "center",
    },
    activityFooter: {
        flexDirection: "row",
        paddingLeft: 12,
        paddingRight: 12,
        justifyContent: "space-between",
        alignItems: "center"
    },
    joinAvator: {
        width: scaleSize(20),
        height: scaleSize(20),
        // backgroundColor: "red",
        borderRadius: 10,
        borderColor: "#fff",
        borderWidth: 1,
    },
    maLeft: {
        marginLeft: -7,
    },
    joinListWarp: {
        flexDirection: "row",
    },
    joinContent: {
        marginLeft: 10,
    },
    joinContentText: {
        color: "#333",
        fontSize: 12,
        fontWeight: "bold"
    },
    activityMoney: {
        width: 56,
        height: 24,
        // backgroundColor: "#EC6138",
        borderRadius: 12,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center"
    },
    activityMoneyText: {
        color: "#EC6138",
        fontSize: 18,
    },
    activityTagWarp: {
        position: "absolute",
        width: 30,
        height: 20,
        // backgroundColor: "red",
    },
    tagText: {
        fontSize: 10,
        textAlign: "center",
        color: "#fff",
        marginTop: 1,
    },
    refreshHeader: {
        alignItems: 'center',
        padding: 20,
    },
    refreshIcon: {
        width: 12,
        height: 12,
        marginBottom: 10,
    },
    refreshText: {
        fontSize: 12,
        color: '#333',
    },
    activityTypeContainer: {
        flexDirection: "row",
        flexWrap: "wrap",
        marginLeft: 12,
        marginRight: 12,
        backgroundColor: "#fff",
        borderBottomWidth: 0.5,
        borderColor: "#E4E6EC",
        borderStyle: "solid"
    },
    activityTypeItem: {
        // paddingLeft: 20,
        // paddingRight: 20,
        width: 72,
        paddingTop: 8,
        paddingBottom: 8,
        borderStyle: "solid",
        borderWidth: 1,
        borderRadius: 20,
        borderColor: "#E4E6EC",
        marginBottom: 12,
    },
    activityTypeActivityItem: {
        width: 72,
        paddingTop: 8,
        paddingBottom: 8,
        borderStyle: "solid",
        borderWidth: 1,
        borderRadius: 20,
        borderColor: "#EC6138",
        marginBottom: 12,
        backgroundColor: "#FFF6F4",
    },
    activityTypeItemText: {
        textAlign: "center",
        color: "#2A2B30",
        fontSize: 12,
    },
    activityTypeActivityItemText: {
        textAlign: "center",
        color: "#EC6138",
        fontSize: 12,
    },
    activityBtnContainer: {
        marginLeft: 12,
        marginRight: 12,
        marginTop: 12,
        paddingBottom: 12,
        flexDirection: "row",
    },
    resetBtn: {
        width: 99,
        height: 40,
        marginRight: 12,
        borderStyle: "solid",
        borderWidth: 1,
        borderRadius: 20,
        flexDirection: "row",
        justifyContent: "center",
        alignItems:"center",
        borderColor: "#E4E6EC"
    },
    ok: {
        flex: 1,
        borderStyle: "solid",
        borderWidth: 1,
        borderRadius: 20,
        flexDirection: "row",
        justifyContent: "center",
        alignItems:"center",
        borderColor: "#E4E6EC",
        backgroundColor: "#EC6138",
    },
    okText: {
        color: "#fff",
    },
    dateContainer: {
        marginLeft: 12,
        marginRight: 12,
    },
    longDateContainer: {
        flexDirection: "row",
        justifyContent: "space-between"
    },
    longDateItem: {
        paddingTop: 6,
        paddingBottom: 6,
        paddingLeft: 30,
        paddingRight: 30,
        backgroundColor: "#F7F8F9",
        borderRadius: 20,
    },
    longDateItemText: {
        fontSize: 12,
        // fontWeight: 400,
    },
    changeTimeTitleContainer: {
        flexDirection: "row",
        alignItems: "center",
        flex: 1,
        paddingRight: 12,
        justifyContent: "flex-end"
    },
    changeTimeIcon: {
        flexDirection:"row",
    },
    changeTimeTitle: {
        fontSize: 12,
        color: "#676978",
        marginRight: 14,
    },
    unLoginContainer: {
        position: "absolute",
        bottom: 0,
        width: "100%",
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        backgroundColor: "#FFEFEB",
        paddingTop: 8,
        paddingBottom: 8,
        paddingLeft: 12,
        paddingRight: 12,
    },
    goLoginTitle: {
        fontSize: 14,
        color: "#EC6138"
    },
    goLogin: {
        width: 72,
        height: 24,
        backgroundColor: "#EC6138",
        borderRadius: 12,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    goLoginText: {
        color: "#fff",
        fontSize: 12,
    },
    // activityContainer: {
    //     // flexDirection: "row",
    //     marginLeft: 12,
    //     marginRight: 12,
    //     height: scaleSize(164),
    //     backgroundColor: "#fff",
    //     borderRadius: 8,
    //     marginBottom: 12,
    // },
    // activitybody: {
    //     padding: 12,
    //     flexDirection: "row",
    //
    // },
    // activityBanner: {
    //     position: "relative",
    //     width: scaleSize(110),
    //     height: scaleSize(110),
    //     backgroundColor: "blue",
    //     borderRadius: 4,
    // },
    // activityContent: {
    //     marginLeft: 10,
    // },
    // activityTitleWarp: {
    //     width: scaleSize(192),
    // },
    // activityTitle: {
    //     fontSize: 16,
    //     fontWeight: "bold",
    //     color: "#2A2B30",
    //     letterSpacing: 1.2,
    //     lineHeight: 22,
    // },
    // addressIcon: {
    //     width: scaleSize(11),
    //     height: scaleSize(11),
    // },
    // activityTag: {
    //     width: scaleSize(28),
    //     height: scaleSize(12),
    //     backgroundColor: "rgba(255,70,0,0.1)",
    //     borderRadius: 10,
    //     marginTop: 6,
    //     marginRight: 5,
    // },
    // activityTagText: {
    //     fontSize: 8,
    //     color: "#EC6138",
    //     textAlign: "center",
    //     lineHeight: 12,
    // },
    // activityDateWarp: {
    //     flexDirection: "row",
    //     alignItems: "center",
    //     marginTop: 6,
    //     marginBottom: 6,
    // },
    // activityDate: {
    //     marginLeft: 3,
    //     fontSize: 12,
    //     color: "#676978"
    // },
    // activityAdressWarp: {
    //     flexDirection: "row",
    //     alignItems: "center",
    // },
    // activityAdress: {
    //     fontSize: 12,
    //     color: "#676978",
    //     marginLeft: 3,
    // },
    // joinList: {
    //     flexDirection: "row",
    //     alignItems: "center",
    // },
    // activityFooter: {
    //     flexDirection: "row",
    //     paddingLeft: 12,
    //     paddingRight: 12,
    //     justifyContent: "space-between",
    //     alignItems: "center"
    // },
    // joinAvator: {
    //     width: scaleSize(20),
    //     height: scaleSize(20),
    //     // backgroundColor: "red",
    //     borderRadius: 10,
    //     borderColor: "#fff",
    //     borderWidth: 1,
    // },
    // maLeft: {
    //     marginLeft: -7,
    // },
    // joinListWarp: {
    //     flexDirection: "row",
    // },
    // joinContent: {
    //     marginLeft: 10,
    // },
    // joinContentText: {
    //     color: "#333",
    //     fontSize: 12,
    //     fontWeight: "bold"
    // },
    // activityMoney: {
    //     width: 56,
    //     height: 24,
    //     backgroundColor: "#EC6138",
    //     borderRadius: 12,
    //     flexDirection: "row",
    //     justifyContent: "center",
    //     alignItems: "center"
    // },
    // activityMoneyText: {
    //     color: "#fff",
    //     fontSize: 18,
    // },
    // activityTagWarp: {
    //     position: "absolute",
    //     width: 30,
    //     height: 20,
    //     // backgroundColor: "red",
    // },
    // tagText: {
    //     fontSize: 10,
    //     textAlign: "center",
    //     color: "#fff",
    //     marginTop: 1,
    // },
    // refreshHeader: {
    //     alignItems: 'center',
    //     padding: 20,
    // },
    // refreshIcon: {
    //     width: 12,
    //     height: 12,
    //     marginBottom: 10,
    // },
    // refreshText: {
    //     fontSize: 12,
    //     color: '#333',
    // },
    isFullingHeight: {
        height: "100%",
    },
    groupStateContainer: {
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",

        paddingRight: 12,
    },
    groupInfoWarp: {
        position: "relative",
        flexDirection: 'row',
        alignItems: "center",
        marginTop: 16,
        marginBottom: 16,
        marginLeft: 24,
        marginRight: 12,
    },
    groupAvator: {
        width: scaleSize(52),
        height: scaleSize(52),
        borderRadius: 50,
        overflow: "hidden",
    },
    groupInfoCotent: {
        marginLeft: 10,
    },
    groupInfoTitle: {
        // fontWeight: "bold",
    },
    groupInfoTotal: {
        color: "#9C9EAC",
        fontSize: 12,
    },
    groupOut: {
        width: 56,
        height: 26,
        borderColor: "#EC6138",
        borderWidth: 1,
        borderRadius: 13,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    groupOutText: {
        color: "#EC6138",
        fontSize: 12,
    },

    groupCreateBtn: {
        width: 56,
        height: 26,
        backgroundColor: "#EC6138",
        borderRadius: 13,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    groupCreateBtnText: {
        color: "#fff",
        fontSize: 12,
    },
    groupContainer: {
        marginHorizontal: 12,
        backgroundColor:"#fff",
        marginBottom: 12,
        borderRadius: 8,
    },
    koneContainer: {
        // margin: 12,
        backgroundColor: "#F7F7F7",
        padding: 12,
        flex: 1,
    },
    koneItem: {
        flexDirection: "row",
        alignItems: "center",
        backgroundColor: "#fff",
        paddingVertical: 12,
        paddingHorizontal: 16,
        borderRadius: 8,
        marginBottom: 12,
    },
    koneAvator: {
        width: 52,
        height: 52,
        overflow: "hidden",
        borderRadius: 50,
    },
    koneContent: {
        flex: 1,
        marginLeft: 10,
    },
    koneContentText: {
        fontSize: 12,
        color: "#2A2B30"
    },
});
